# -*- coding: utf-8 -*-
from nmj.scanners.movie import NMJImage
from nmj.scanners.tmdb import TMDBMovie
from nmj.sqlite.nmj_db import NMJ_SERIE_TYPE
from tvdb_api import Tvdb
from tvdb_ui import BaseUI
import logging

_LOGGER = logging.getLogger(__name__)

class TheTVDbScanner(object):
	def __init__(self):
		self._webapi = Tvdb(
			interactive=False,
			select_first=False,
			debug=False,
			cache=True,
			banners=True,
			actors=True,
			custom_ui=self._get_custom_ui(),
			language="fr",
			search_all_languages=False,
			apikey="5BA46DFDB0AB740E",
			forceConnect=False)
		self.all_propositions = []

	def _get_custom_ui(self):
		class CustomUi(BaseUI):
			def selectSeries(instance, allSeries): # @NoSelf
				self.all_propositions = allSeries
				return allSeries[0]
		return CustomUi

	def raw_search(self, string):
		return self._webapi[string]

	def get_propositions(self, string, season=None, episode=None):
		best_result = self.to_nmj_movie(self.raw_search(string), season=season, episode=episode)
		shows = [best_result]
		for proposition in self.all_propositions:
			imdb_id = proposition.get("imdb_id", None)
			if not imdb_id or imdb_id != best_result.imdb_id:
				show = self.to_nmj_movie(self._webapi[proposition["id"]], season=season, episode=episode)
				shows.append(show)
		return shows

	def search(self, string, season=None, episode=None, **_kwargs):
		try:
			return self.get_propositions(string, season, episode)
		except:
			_LOGGER.exception("Failed to find show for %s", string)
			return []

	def __get_episode_details(self, show, season, episode):
		episode_title = ""
		director = ""
		try:
			if season:
				episode = show[int(season)][int(episode)]
				episode_title = episode["episodename"]
				director = episode["director"]
			elif episode:
				for season in show:
					for episode_number in show[season]:
						episode_obj = show[season][episode_number]
						if episode_obj["absolute_number"] == episode:
							episode_title = episode_obj["episodename"]
							director = episode_obj["director"]
			return (episode_title, director)
		except:
			return (show["seriesname"], director)

	def to_nmj_movie(self, show, season=None, episode=None):
		title, director = self.__get_episode_details(show, season, episode)
		movie = TMDBMovie(
			tmdb_id=show["id"],
			imdb_id=show["imdb_id"],
			title=show["seriesname"],
			synopsis=show["overview"],
			short_synopsis=show["overview"],
			posters=[NMJImage(poster, thumb) for poster, thumb in self.get_posters(show)],
			fanarts=[NMJImage(fanart, thumb) for fanart, thumb in self.get_fanarts(show)],
			genres=show.get("genre", "").strip("|").split("|"),
			cast={"actor":show["_actors"], "director" : [{"name" : director}]},
			show_type=NMJ_SERIE_TYPE,
		)
		if season and episode:
			episode_name = "S%02dE%02d" % (int(season), int(episode))
		elif season:
			episode_name = "S%02d" % int(season)
		else:
			episode_name = "%03d" % int(episode) or ""
		movie.update_attr(
			season=season or "",
			episode=episode_name or "",
			release_date=show["firstaired"],
			runtime=int(show.get("runtime", 0)) * 60,
			rating=float(show.get("rating", 0)),
			episode_title=title,
		)
		movie.get_media = lambda:movie
		return movie

	def get_fanarts(self, show):
		return self.__get_images(show, "fanart")

	def get_posters(self, show):
		return self.__get_images(show, "poster")

	def __get_images(self, show, image_type):
		result = []
		try:
			for _, images in show["_banners"][image_type].iteritems():
				for _, image_data in images.iteritems():
					if int(image_data["ratingcount"]):
						rating = float(image_data["rating"])
					else:
						rating = 0
					full_url = image_data["_bannerpath"]
					thumb_url = image_data.get("_thumbnailpath", full_url)
					result.append((rating, full_url, thumb_url))
		except KeyError:
			pass
		result.sort(key=lambda x:x[0])
		result.reverse()
		return [(url, thumb) for (_, url, thumb) in result]

	def get_season(self, show, rank):
		return show[rank]

	def get_episode(self, season, rank):
		return season[rank]

	def get_media(self, id):
		pass

if __name__ == "__main__":

	scanner = TheTVDbScanner()
	for proposition in scanner.search("Lost", episode=1):
		print proposition.title

#	webapi = Tvdb(
#		interactive=False,
#		select_first=False,
#		debug=False,
#		cache=True,
#		banners=True,
#		actors=True,
#		language="fr",
#		search_all_languages=False,
#		apikey="5BA46DFDB0AB740E",
#		forceConnect=False)
#	import pprint
#	pprint.pprint(webapi["The Vampire Diaries"]["_banners"]["fanart"])
#	new_s = ""
#	for c in unicode(s):
#		if ord(c) < 128:
#			new_s += c
#	print new_s, dict(s)
#	print show["_banners"]["poster"]
#	print show["_banners"]["fanart"]
#	season1 = scanner.get_season(show, 1)
#	print season1
#	episode1 = scanner.get_episode(season1, 1)
#	pprint.pprint(episode1.items())



